package com.work.music.utils;

import com.work.music.common.HttpRequestParamter;
import com.work.music.exception.AjaxOperationFailException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

public class FileUploadUtil {
    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws AjaxOperationFailException
     */
    public static String uploadImage(MultipartFile file, String imgType) throws AjaxOperationFailException {
        if (file == null) {
            throw new AjaxOperationFailException("未选择文件");
        }
        String suffix = HttpRequestParamter.getString("suffix");

        String originalFilename = file.getOriginalFilename();
        if(StringUtil.isNull(originalFilename))
            return "";
        String fileName = imgType + DateUtil.format(new Date(), "yyyyMMddHHmmss") + StringUtil.getRandomString(4, 2) + "."
                + (StringUtil.isEmpty(suffix) ?  originalFilename.substring(originalFilename.lastIndexOf(".") + 1): suffix);
        String filePath = StringUtil.IMGPATH + fileName;

        File destFile = new File(filePath);
        try {
            if (!destFile.exists()) {
                if (!destFile.getParentFile().exists()) {
                    if (!destFile.getParentFile().mkdirs()) {
                        throw new AjaxOperationFailException("无法创建文件夹");
                    }
                }
                if (!destFile.createNewFile()) {
                    throw new AjaxOperationFailException("无法创建文件");
                }
            }

            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new AjaxOperationFailException("无法写入文件");
        }

        return fileName;
    }
}
